package com.easytopit.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.easytopit.demo.domain.Movie;
import com.easytopit.demo.domain.Score;
import com.easytopit.demo.domain.User;
import com.easytopit.demo.service.MovieService;
import com.easytopit.demo.service.OrderService;
import com.easytopit.demo.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private MovieService movieService;
	
	private String nums;
	
	/**
	 * 主页
	 * @return
	 */
	@RequestMapping(value="/")
	public String index(ModelMap modelMap){
		List<String> movie =  movieService.queryMovieByStatus("正在上映");
		List<String> futureMovies = movieService.queryMovieByStatus("即将上映");
		List<String> types = new LinkedList<>();
		List<String> actors = new LinkedList<>();
		List<Score> scores = new LinkedList<>();
		List<Movie> movies = new LinkedList<>();
		for(int i = 0; i < movie.size(); i++){
			movies = movieService.queryMovieByName(movie.get(i));
		}
		for(Movie m : movies){
			if(m!=null){
				types = movieService.queryTypeByName(m.getName());
				actors = movieService.queryActorByName(m.getName());
				scores = movieService.queryScoreByName(m.getName());
			}
		}
		modelMap.put("movies", movies);
		modelMap.put("futureMovies", futureMovies);
		modelMap.put("types", types);
		modelMap.put("actors", actors);
		modelMap.put("scores", scores);
		return "index/index";
	}
	
	//注册页面
	@RequestMapping(value="/reg")
	public String regPage(){
		return "user/reg";
	}
	
	//注册
	@RequestMapping(value="/reg.do",method = RequestMethod.GET)
	public String reg(String name,String passwd,String surePasswd,ModelMap modelMap){
		if(userService.check(name)==null){
			if(passwd.equals(surePasswd)){
				userService.reg(name, passwd, surePasswd);
				return "user/login";
			}
			modelMap.put("mes", "两次输入密码不一致");
			return "user/reg";
		}
		modelMap.put("mes", "该用户名已被注册");
		return "user/reg";
	}
	
	//登录页面
	@RequestMapping(value="/login")
	public String loginPage(){
		return "user/login";
	}
	
	//登录
	@RequestMapping(value="/login.do",method = RequestMethod.GET)
	public String login(String name,String passwd,HttpSession httpSession,ModelMap modelMap){
		User user = userService.user(name, passwd);
		if(user!=null){
			httpSession.setAttribute("USER_NAME", name);
			if(user.getName().equals("admin")){
				return "index/adminIndex";//管理员中心
			}
			List<String> movie =  movieService.queryMovieByStatus("正在上映");
			List<String> futureMovie = movieService.queryMovieByStatus("即将上映");
			User userInfo = userService.user(name, passwd);
			List<Movie> movies = new LinkedList<>();
			for(int i = 0; i < movie.size(); i++){
				movies = movieService.queryMovieByName(movie.get(i));
			}
			List<Movie> futureMovies = new LinkedList<>();
			for(int i = 0; i < futureMovie.size(); i++){
				futureMovies = movieService.queryMovieByName(futureMovie.get(i));
			}
			modelMap.put("movies", movies);
			modelMap.put("futureMovies", futureMovies);
			modelMap.put("name", userInfo.getName());
			modelMap.put("passwd", userInfo.getPasswd());
			modelMap.put("face", userInfo.getFace());
			return "index/userIndex";
		}
		modelMap.put("mes", "用户名或密码错误");
		return "user/login";
	}
	
	//注销
	@RequestMapping(value="/logout")
	public String logout(HttpSession httpSession){
		httpSession.invalidate();
		return "user/login";
	}
	
	//修改密码页面
	@RequestMapping(value="/updatePasswd")
	public String upPasswdPage(){
		return "user/updatePasswd";
	}
	
	//修改密码
	@RequestMapping(value="/updatePasswd.do",method = RequestMethod.GET)
	public String upPasswd(String oldPasswd,String passwd,String surePasswd,HttpSession httpSession,ModelMap modelMap){
		String name = (String) httpSession.getAttribute("USER_NAME");
		if(name!=null){
			if(userService.user(name, oldPasswd)!=null){
				if(passwd.equals(surePasswd)){
					userService.updatePasswd(name, passwd);
					modelMap.put("mes", "修改成功");
					return "index/selfIndex";
				}
				modelMap.put("mes", "两次输入密码不一致");
				return "user/updatePasswd";
			}
			modelMap.put("mes", "旧密码输入错误");
			return "user/updatePasswd";
		}
		modelMap.put("mes", "尚未登录");
		return "user/login";
	}
	
	/**
	 * 设置头像
	 * @return
	 */
	@RequestMapping(value="/setFace")
	public String setFacePage(){
		return "user/setFace";
	}
	
	@RequestMapping(value="/setFace.do",method = RequestMethod.POST)
	public String setFace(@RequestParam("face")MultipartFile file,HttpServletRequest request,HttpSession httpSession,
			ModelMap modelMap) throws IOException, ServletException{
		String name = (String) httpSession.getAttribute("USER_NAME");
		if(name!=null){
			int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
			String oriFileNameSuffix = lastIndexOf != -1 ? file.getOriginalFilename().substring(lastIndexOf): "";
			// 后缀集
			List<String> suffixs = Arrays.asList(".png", ".jpg", ".jpeg", ".gif", ".PNG", ".JPG", ".JPEG", ".GIF");
			if (!suffixs.contains(oriFileNameSuffix)) {
				// 回显信息
				modelMap.put("mes", "请上传图片");
				// 识别
				return "forward:/setFace";
			}
			String destFileName = UUID.randomUUID() + oriFileNameSuffix;
			String destFilePath = request.getServletContext().getRealPath("/") + "/upload/";
			File destFile = new File(destFilePath, destFileName);
			if(!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
			file.transferTo(destFile);
			userService.setFace(destFileName, name);
			modelMap.put("face", destFileName);
			return "index/selfIndex";
		}
		modelMap.put("mes", "尚未登录");
		return "index/index";
	}
	
	/**
	 * 设置邮箱
	 * @return
	 */
	@RequestMapping(value="/setEmail")
	public String setEmailPage(){
		return "user/setEmail";
	}
	
	@RequestMapping(value="/setEmail.do",method = RequestMethod.GET)
	public String setEmail(String email,HttpSession httpSession,ModelMap modelMap){
		String name = (String) httpSession.getAttribute("USER_NAME");
		if(name!=null){
			// 以下地址可到对应邮箱服务商帮助下查找 SMTP地址以及密码等
			JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
			// smtp 发送地址
			mailSender.setHost("smtp.qq.com");
			// stmp 发送端口
			mailSender.setPort(465);
	
			// JAVA MAIL 就是一个邮箱客户端, 所以需要登录: 用户名/密码
			mailSender.setUsername("735507827@qq.com");
			mailSender.setPassword("rqyezktfadzmbbgi");
	
			// 配置邮件客户端的基础配置
			Properties props = mailSender.getJavaMailProperties();
			// 发送协议smtp
			props.put("mail.transport.protocol", "smtp");
			// 是否需要安全鉴定
			props.put("mail.smtp.auth", "true");
			// 是否加密
			props.put("mail.smtp.ssl.enable", "true");
			// 输出调试信息
			props.put("mail.debug", "true");
			// 设置发件人: 省去每次单独simpleMailMessage.setFrom("qspan@easytopit.com");
			props.put("mail.from", "735507827@qq.com");
			// 创建一封简单的邮箱
			SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
			// 收到邮箱显示的标题
			simpleMailMessage.setSubject("欢迎使用interesting电影~");
			// 发送给对方: 邮箱
			simpleMailMessage.setTo(email);
			// 标识本人
			simpleMailMessage.setFrom("735507827@qq.com");
			// 邮箱内容
			Random random = new Random();
			int num = random.nextInt(10000);
			nums = String.valueOf(num);
			simpleMailMessage.setText("验证码:"+num);
			// 标志发送日期
			simpleMailMessage.setSentDate(new Date());
			
			// 发送
			mailSender.send(simpleMailMessage);
			modelMap.put("email", email);
			return "user/checkCode";
		}
		modelMap.put("mes", "尚未登录");
		return "user/login";
	}
	
	@RequestMapping(value="/checkCode.do",method = RequestMethod.GET)
	public String checkCode(String email,String code,HttpSession httpSession,ModelMap modelMap){
		System.out.println(code);
		System.out.println(nums);
		String name = (String) httpSession.getAttribute("USER_NAME");
		if(code.equals(nums)){
			userService.setEmail(email, name);
			modelMap.put("mes", "成功绑定邮箱");
			return "index/selfIndex";
		}
		modelMap.put("email", email);
		modelMap.put("mes", "验证码错误");
		return "user/checkCode";
	}
	
	@RequestMapping(value="/selfIndex")
	public String selfCenterPage(){
		return "index/selfIndex";
	}
	
	@RequestMapping(value="/userInfo")
	public String userInfoPage(HttpSession httpSession,ModelMap modelMap){
		String name = (String) httpSession.getAttribute("USER_NAME");
		modelMap.put("userName", name);
		modelMap.put("userBalance", orderService.userBalance(name));
		return "user/userInfo";
	}
	
	@RequestMapping(value="/userComment")
	public String userCommentPage(){
		return "user/userComment";
	}
}